import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userAPI } from '@/api/index.js'

export const useUserStore = defineStore('user', () => {
  // 登录状态
  const isLoggedIn = ref(false)
  
  // 用户信息
  const userInfo = ref({
    id: null,
    userAccount: '',
    nickname: '',
    email: '',
    phone: '',
    userAvatar: '',
    userProfile: '',
    position: '',
    company: '',
    location: '',
    website: '',
    githubUrl: '',
    weiboUrl: '',
    userRole: '',
    createTime: '',
    updateTime: ''
  })
  
  // 从后端获取当前用户信息
  const fetchUserInfo = async () => {
    try {
      console.log('正在获取用户信息...')
      const response = await userAPI.getCurrentUser()
      console.log('获取用户信息响应:', response)
      
      if (response.code === 0 && response.data) {
        const userData = response.data
        userInfo.value = {
          id: userData.id,
          userAccount: userData.userAccount || '',
          nickname: userData.nickname || '',
          email: userData.email || '',
          phone: userData.phone || '',
          userAvatar: userData.userAvatar || '/touxiang.jpg',
          userProfile: userData.userProfile || '',
          position: userData.position || '',
          company: userData.company || '',
          location: userData.location || '',
          website: userData.website || '',
          githubUrl: userData.githubUrl || '',
          weiboUrl: userData.weiboUrl || '',
          userRole: userData.userRole || '',
          createTime: userData.createTime || '',
          updateTime: userData.updateTime || ''
        }
        
        isLoggedIn.value = true
        
        // 保存到localStorage
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        localStorage.setItem('userId', userData.id?.toString() || '')
        
        console.log('用户信息更新成功:', userInfo.value)
        return true
      } else {
        console.log('获取用户信息失败:', response.message)
        return false
      }
    } catch (error) {
      console.error('获取用户信息时发生错误:', error)
      return false
    }
  }
  
  // 登录方法（保持兼容性，但建议使用fetchUserInfo）
  const login = async (loginData) => {
    // 如果传入的是旧格式参数（向后兼容）
    if (typeof loginData === 'string') {
      const nickname = loginData;
      const avatar = arguments[1] || '/touxiang.jpg';
      const userId = arguments[2] || null;
      
      isLoggedIn.value = true
      userInfo.value.nickname = nickname
      userInfo.value.userAvatar = avatar
      userInfo.value.id = userId
      
      // 保存到localStorage
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      if (userId) {
        localStorage.setItem('userId', userId.toString())
      }
      return true;
    }
    
    // 新的登录逻辑 - 简化版，任何账号密码都能登录成功
    const { userAccount, userPassword } = loginData;
    
    // 不再进行账号密码验证，直接设置管理员用户信息
    userInfo.value = {
      id: 1,
      userAccount: userAccount || 'admin',
      nickname: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      userAvatar: '/touxiang.jpg',
      userProfile: '系统管理员',
      position: '管理员',
      company: '技术部',
      location: '北京',
      website: '',
      githubUrl: '',
      weiboUrl: '',
      userRole: 'admin', // 强制设置为管理员角色
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
    
    isLoggedIn.value = true;
    
    // 保存到localStorage
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
    localStorage.setItem('userId', '1');
    
    return true;
  }
  
  // 退出登录方法
  const logout = () => {
    isLoggedIn.value = false
    userInfo.value = {
      id: null,
      userAccount: '',
      nickname: '',
      email: '',
      phone: '',
      userAvatar: '',
      userProfile: '',
      position: '',
      company: '',
      location: '',
      website: '',
      githubUrl: '',
      weiboUrl: '',
      userRole: '',
      createTime: '',
      updateTime: ''
    }
    
    // 清除localStorage
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('userId')
    localStorage.removeItem('token')
  }
  
  // 初始化用户状态（从localStorage恢复或从API获取）
  const initUserState = async () => {
    const savedLoginState = localStorage.getItem('isLoggedIn')
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedUserId = localStorage.getItem('userId')
    
    if (savedLoginState === 'true' && (savedUserInfo || savedUserId)) {
      // 如果有保存的登录状态，先尝试从API获取最新用户信息
      const success = await fetchUserInfo()
      
      if (!success && savedUserInfo) {
        // 如果API获取失败，使用本地保存的信息
        try {
          isLoggedIn.value = true
          userInfo.value = JSON.parse(savedUserInfo)
          console.log('使用本地保存的用户信息')
        } catch (error) {
          console.error('解析本地用户信息失败:', error)
          logout()
        }
      }
    }
  }
  
  // 检查是否需要登录
  const requireLogin = () => {
    return !isLoggedIn.value
  }
  
  return {
    isLoggedIn,
    userInfo,
    login,
    logout,
    initUserState,
    requireLogin,
    fetchUserInfo
  }
})